package org.eclipse.football;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class KickerServlet extends HttpServlet implements Servlet {
	// Override doPost function
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Read in information submitted by form
		String button = request.getParameter("Kicker Button");
		
		// Obtain existing team
		Team team = (Team) request.getSession(true).getAttribute("team");
		
		// Obtain existing league
		League league = (League) request.getSession(true).getAttribute("league");
		
		// Declare a kicker variable
		Kicker player;
		
		if (button.equals("Add Kicker")){
			// Get name and team all on one line from selected input parameter
			String kicker = request.getParameter("kicker");
			
			// Parse kicker to get player name and team name
			String name = kicker.split(",")[0];
			String team_name = kicker.split(",")[1];
			
			// Make sure that new players name is not null or blank and team is not null
				// and team name is neither blank nor null
			if(name != null && !name.equalsIgnoreCase("") && team != null
					&& team_name != null && !team_name.equalsIgnoreCase("")){
				// If not then create a player with the given name and team
				player = new Kicker(name, team_name);
		
				// Add the new player to this team
				team.addKicker(player);
			}
		}
		else if (button.equals("Fire!")){
			String name = request.getParameter("name");
			String team_name = request.getParameter("team");
			
			if(name != null && !name.equalsIgnoreCase("") && team != null
					&& team_name != null && !team_name.equalsIgnoreCase("")){
				player = new Kicker(name, team_name);
				team.removeKicker(player);
			}
		}
		
		// Write the current state of the league out to a file
		league.writeState("league.txt");
		
		// Set league in the session
		request.getSession().setAttribute("league", league);
		
		// Set team in the session
		request.getSession().setAttribute("team", team);

		// Set all 3 player types to null in the session
		request.getSession().setAttribute("off", null);
		request.getSession().setAttribute("def", null);
		request.getSession().setAttribute("kicker", null);
		
		// Forward control back to stats.jsp
		getServletContext().getRequestDispatcher("/TeamPage.jsp").forward(request, response);
		
		// TODO Auto-generated method stub
		//super.doPost(request, response);
	}

}

